package com.xiaoxing.gongqiju.mvp.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.gongqiju.R;
import com.xiaoxing.gongqiju.R2;
import com.xiaoxing.gongqiju.di.component.DaggerLiaoCheng_GongQiJu_KuCunLieBiaoComponent;
import com.xiaoxing.gongqiju.di.module.LiaoCheng_GongQiJu_KuCunLieBiaoModule;
import com.xiaoxing.gongqiju.mvp.contract.LiaoCheng_GongQiJu_KuCunLieBiaoContract;
import com.xiaoxing.gongqiju.mvp.presenter.LiaoCheng_GongQiJu_KuCunLieBiaoPresenter;
import com.xiaoxing.gongqiju.mvp.ui.adapter.LiaoCheng_GongQiJu_KuCunLieBiaoAdapter;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_KuCunLieBiao;
import com.xiaoxing.gongqiju.mvp.ui.entity.LiaoCheng_GongQiJu_RuKuCaoZuo;
import com.xiaoxing.gongqiju.mvp.ui.entity.QueryDataMaterialClassSelect;
import com.xiaoxing.gongqiju.mvp.ui.entity.QueryDataMaterialGroupSelect;
import com.xiaoxing.gongqiju.mvp.ui.utils.PrinterUtil;
import com.xw.repo.XEditText;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.GONGQIJU_LIAOCHENG_ACTIVITY_LIAO_CHENG_GONG_QI_JU_KU_CUN_LIE_BIAO)
public class LiaoCheng_GongQiJu_KuCunLieBiaoActivity extends BaseActivity<LiaoCheng_GongQiJu_KuCunLieBiaoPresenter> implements LiaoCheng_GongQiJu_KuCunLieBiaoContract.View, OnRefreshListener, LiaoCheng_GongQiJu_KuCunLieBiaoAdapter.ILiaoCheng_GongQiJu_KuCunLieBiaoAdapter, PrinterUtil.PrinterI {


    private static boolean mIsNeedDemo = true;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;

    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    PrinterUtil mPrinterUtil;
    @BindView(R2.id.ns_gong_ju_wu_liao_zu)
    NiceSpinner nsGongJuWuLiaoZu;
    @BindView(R2.id.ns_gong_ju_lei_bie)
    NiceSpinner nsGongJuLeiBie;
    @BindView(R2.id.ns_cang_wei)
    NiceSpinner nsCangWei;
    @BindView(R2.id.xet_gong_ju_ming_cheng)
    XEditText xetGongJuMingCheng;
    private LiaoCheng_GongQiJu_KuCunLieBiaoAdapter mAdapter;
    private List<LiaoCheng_GongQiJu_KuCunLieBiao.DataBean> mDataBeanList = new ArrayList<>();
    private String mGongJuWuLiaoZuName;
    private String mGongJuWuLiaoZuId;
    private String mnsGongJuLeiBieName;
    private String mnsGongJuLeiBieId;
    private String mnsCangWeiName;
    private String mnsCangWeiId;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiaoCheng_GongQiJu_KuCunLieBiaoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .liaoCheng_GongQiJu_KuCunLieBiaoModule(new LiaoCheng_GongQiJu_KuCunLieBiaoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_liao_cheng__gong_qi_ju__ku_cun_lie_biao; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_liao_cheng__gong_qi_ju__ku_cun_lie_biao));
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);

        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        getQueryDataMaterialClassSelect();
        getQueryDataMaterialGroupSelect();
        getLiaoCheng_GongQiJu_RuKuCaoZuoList();
    }

    private void getLiaoCheng_GongQiJu_RuKuCaoZuoList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        mPresenter.getLiaoCheng_GongQiJu_RuKuCaoZuoList(map);
    }

    private void getQueryDataMaterialClassSelect() {
        HashMap<String, String> map = new HashMap<>();
        map.put("queryname", "");
        mPresenter.getQueryDataMaterialClassSelect(map);
    }

    private void getQueryDataMaterialGroupSelect() {
        HashMap<String, String> map = new HashMap<>();
        map.put("queryname", "");
        mPresenter.getQueryDataMaterialGroupSelect(map);
    }

    @Override
    public void getQueryDataMaterialGroupSelectDataSuccess(QueryDataMaterialGroupSelect entityList) {
        if (entityList.getData() != null)
            bindQueryDataMaterialGroupSelect(entityList.getData());
    }

    // 物料组下拉选
    private void bindQueryDataMaterialGroupSelect(List<QueryDataMaterialGroupSelect.DataBean> queryDataMaterialGroupSelects) {

        ArrayList<String> dataNames = new ArrayList();
        ArrayList<String> dataSids = new ArrayList();
        dataNames.add("请选择");
        dataSids.add("");
        for (int i = 0; i < queryDataMaterialGroupSelects.size(); i++) {
            dataNames.add(queryDataMaterialGroupSelects.get(i).getMtname());
            dataSids.add(String.valueOf(queryDataMaterialGroupSelects.get(i).getMtid()));
        }
        nsGongJuWuLiaoZu.attachDataSource(dataNames);
        mGongJuWuLiaoZuName = "";
        mGongJuWuLiaoZuId = "";

        nsGongJuWuLiaoZu.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mGongJuWuLiaoZuName = "";
                    mGongJuWuLiaoZuId = "";
                } else {
                    mGongJuWuLiaoZuName = dataNames.get(position);
                    mGongJuWuLiaoZuId = dataSids.get(position);
                }
            }
        });

    }

    @OnClick(R2.id.btn_cha_xun)
    public void onViewClicked() {


        mDataBeanList.clear();
        mAdapter.notifyDataSetChanged();
        mEmptyLayout.setVisibility(View.VISIBLE);
        mRecyclerView.setVisibility(View.GONE);
        getLiaoCheng_GongQiJu_KuCunLieBiaoList();
    }

    @Override
    public void getQueryDataMaterialClassSelectDataSuccess(QueryDataMaterialClassSelect entityList) {
        if (entityList.getData() != null)
            bindQueryDataMaterialClassSelect(entityList.getData());
    }

    @Override
    public void getLiaoCheng_GongQiJu_RuKuCaoZuoDataSuccess(LiaoCheng_GongQiJu_RuKuCaoZuo entityList) {
        if (entityList.getData() != null)
            bindCangWei(entityList.getData());
    }

    private void bindCangWei(List<LiaoCheng_GongQiJu_RuKuCaoZuo.DataBean> dataBeans) {

        ArrayList<String> dataNames = new ArrayList();
        ArrayList<String> dataSids = new ArrayList();
        dataNames.add("请选择");
        dataSids.add("");
        for (int i = 0; i < dataBeans.size(); i++) {
            dataNames.add(dataBeans.get(i).getSpname());
            dataSids.add(String.valueOf(dataBeans.get(i).getSpid()));
        }
        nsCangWei.attachDataSource(dataNames);
        mnsCangWeiName = "";
        mnsCangWeiId = "";

        nsCangWei.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mnsCangWeiName = "";
                    mnsCangWeiId = "";
                } else {
                    mnsCangWeiName = dataNames.get(position);
                    mnsCangWeiId = dataSids.get(position);
                }

            }
        });

    }

    // 工具列表下拉选
    private void bindQueryDataMaterialClassSelect(List<QueryDataMaterialClassSelect.DataBean> queryDataMaterialClassSelects) {

        ArrayList<String> dataNames = new ArrayList();
        ArrayList<String> dataSids = new ArrayList();
        dataNames.add("请选择");
        dataSids.add("");
        for (int i = 0; i < queryDataMaterialClassSelects.size(); i++) {
            dataNames.add(queryDataMaterialClassSelects.get(i).getMcname());
            dataSids.add(String.valueOf(queryDataMaterialClassSelects.get(i).getMcid()));
        }
        nsGongJuLeiBie.attachDataSource(dataNames);
        mnsGongJuLeiBieName = "";
        mnsGongJuLeiBieId = "";

        nsGongJuLeiBie.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    mnsGongJuLeiBieName = "";
                    mnsGongJuLeiBieId = "";
                } else {
                    mnsGongJuLeiBieName = dataNames.get(position);
                    mnsGongJuLeiBieId = dataSids.get(position);
                }

            }
        });

    }

    private void printBigQRcodeOriention(String content) {

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.setItemHorizontalAlignment(LPAPI.ItemAlignment.LEFT);
        api.setItemOrientation(180);

        api.startJob(50 * 100, 50 * 100);//48, 50
//        api.setItemOrientation(180);

        // 开始一个页面的绘制，绘制二维码

        api.drawText("序号:" + content, 30 * 100, 8 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        api.draw2DQRCode(content, 14 * 100, 11 * 100, 20 * 100);//  9, 10, 20,30

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);

    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#D8D8D8"));
        empty_text.setText("暂无数据");
    }

    private List<LiaoCheng_GongQiJu_KuCunLieBiao.DataBean> loadModels() {
        List<LiaoCheng_GongQiJu_KuCunLieBiao.DataBean> lists = new ArrayList<>();

        for (int i = 0; i < 5; i++) {

            LiaoCheng_GongQiJu_KuCunLieBiao.DataBean dataBean = new LiaoCheng_GongQiJu_KuCunLieBiao.DataBean();
            lists.add(dataBean);
        }

        return lists;
    }

    private void initRecyclerView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(LiaoCheng_GongQiJu_KuCunLieBiaoActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new LiaoCheng_GongQiJu_KuCunLieBiaoAdapter(LiaoCheng_GongQiJu_KuCunLieBiaoActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.autoRefresh();
        mRefreshLayout.setEnableLoadMore(false);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

        //getLiaoCheng_GongQiJu_KuCunLieBiaoList();
        mRefreshLayout.finishRefresh();
        mEmptyLayout.setVisibility(View.GONE);

    }

    @Override
    public void getLiaoCheng_GongQiJu_KuCunLieBiaoDataSuccess(LiaoCheng_GongQiJu_KuCunLieBiao entityList) {

        if (entityList != null && entityList.getData() != null && entityList.getData().size() > 0) {
            mDataBeanList.clear();
            mDataBeanList.addAll(entityList.getData());
            mAdapter.notifyDataSetChanged();
            mEmptyLayout.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        } else {
            mEmptyLayout.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        }

    }

    @NotNull
    private String getGongJuMingCheng() {
        return xetGongJuMingCheng.getText().toString().trim();
    }

    private void getLiaoCheng_GongQiJu_KuCunLieBiaoList() {
        HashMap<String, String> map = new HashMap<>();
        map.put("materialtoolname", getGongJuMingCheng());
        map.put("materialgroupId", mGongJuWuLiaoZuId);
        map.put("materialclassid", mnsGongJuLeiBieId);
        map.put("spid", mnsCangWeiId);
        mPresenter.getLiaoCheng_GongQiJu_KuCunLieBiaoList(map);
    }


    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);

    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void daYinErWeiMa(LiaoCheng_GongQiJu_KuCunLieBiao.DataBean item) {
        if (!mPrinterUtil.selectPrinterCheck()) {
            showMessage("打印机未连接");
            return;
        }
        printBigQRcodeOriention(item.getMid());
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {

    }

    @Override
    public void onPrintProgress(String info) {

    }

    @Override
    public void onPrinterDiscovery(String info) {

    }

    @Override
    public void connectSuccess(String info) {

    }

    @Override
    public void Connecting(String info) {

    }

    @Override
    public void connectFail(String info) {

    }

    @Override
    public void printSuccess() {

    }

    @Override
    public void printFail() {

    }
}
